package com.example.dqhl.recycleviewdemo.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.example.dqhl.recycleviewdemo.R;
import com.example.dqhl.recycleviewdemo.adapter.BlueAdapter;
import com.example.dqhl.recycleviewdemo.adapter.MyAdapter;
import com.example.dqhl.recycleviewdemo.modle.MyModle;
import com.example.dqhl.recycleviewdemo.service.BluetoothReceiver;
import com.example.dqhl.recycleviewdemo.util.Common;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by dell on 2017/10/31.
 */

public class BluetoothActivity extends Activity implements View.OnClickListener {

    enum ServerOrCilent {
        NONE,
        SERVICE,
        CILENT
    }

    private RecyclerView recyclerView;
    private TextView tV_search;
    private BluetoothAdapter bluetoothAdapter = null;
    private BlueAdapter myAdapter;
    private List<MyModle> myModles = new ArrayList<>();

    static String BlueToothAddress = "null";
    static ServerOrCilent serviceOrCilent = ServerOrCilent.NONE;


    public clientThread clientConnectThread = null;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth);
        initData();
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void initData() {
        (recyclerView) = (RecyclerView) findViewById(R.id.recyceView);
        (tV_search) = (TextView) findViewById(R.id.tv_search);
        tV_search.setOnClickListener(this);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(myAdapter = new BlueAdapter(this, myModles));

        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!bluetoothAdapter.isEnabled()) {
            //若没打开则打开蓝牙
//            bluetoothAdapter.enable();
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, 3);

        }

        // 当设备被发现时，注册为广播
        IntentFilter discoveryFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(mReceiver, discoveryFilter);

        // 当发现完成时，注册广播
        IntentFilter foundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(mReceiver, foundFilter);

        Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                myModles.add(new MyModle(device.getAddress(), device.getName()));
                myAdapter.notifyDataSetChanged();
            }
        } else {
            myAdapter.notifyDataSetChanged();
        }
    }

    private void initView() {

        myAdapter.setOnItemClickListener(new BlueAdapter.onItemClickListener() {
            //点击每一项增加
            @Override
            public void onItemClick(View view, int position) {
                MyModle item = myModles.get(position);
                String name = item.getName();
                String address = name.substring(name.length() - 17);
                BlueToothAddress = address;

                AlertDialog.Builder StopDialog = new AlertDialog.Builder(BluetoothActivity.this);//定义一个弹出框对象
                StopDialog.setTitle("连接");//标题
                StopDialog.setMessage(item.getAddress());
                StopDialog.setPositiveButton("连接", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        tV_search.setText("重新搜索");
                        serviceOrCilent = ServerOrCilent.CILENT;
                        onStartCon();
                    }
                });
                StopDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        BlueToothAddress = null;
                    }
                });
                StopDialog.show();
            }


            //长按删除
            @Override
            public void onItemLongClick(View view, int position) {
            }
        });
    }

    private void onStartCon() {
        if (serviceOrCilent == ServerOrCilent.CILENT) {
            String address = BlueToothAddress;
            if (!address.equals("null")) {
//
//                Common.device = Common.mBluetoothAdapter.getRemoteDevice(address);
//                Common.device2 = Common.mBluetoothAdapter.getRemoteDevice("00:01:95:26:AF:C4");
                clientConnectThread = new clientThread();
                clientConnectThread.start();
            } else {
                Toast.makeText(BluetoothActivity.this, "address is null !", Toast.LENGTH_SHORT).show();
            }
        }
    }

    //开启客户端
    private class clientThread extends Thread {
        public clientThread() {

        }

        @Override
        public void run() {

            try {
                for (int i = 0; i < Common.bleSocket.size(); i++) {
                    Common.bleSocket.get(i).connect();

                    if (Common.bleSocket.get(i) != null) {

                        Log.d("WWDZ", "第" + i + "个socket连接 ok");
                    }
                }
//
                Message msg = new Message();
                msg.obj = "已经全部连接上服务端！可以发送信息。";
                msg.what = 0;
                LinkDetectedHandler.sendMessage(msg);
                Log.i("WWDZ", "已连接成功1==");
                Toast.makeText(BluetoothActivity.this, "已连接成功", Toast.LENGTH_SHORT).show();
//                Intent intent = new Intent(BluetoothActivity.this, WorkView.class);
//                startActivity(intent);

                //启动接受数据
            } catch (IOException e) {
                Log.e("connect", "", e);
                Message msg = new Message();
                msg.obj = "连接服务端异常！请检查网络！";
                msg.what = 0;
                LinkDetectedHandler.sendMessage(msg);
            }
        }
    }

    //消息连接Hander;
    private Handler LinkDetectedHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Toast.makeText(BluetoothActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
        }

    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_search:
                // TODO Auto-generated method stub
                if (bluetoothAdapter.isDiscovering()) {
                    bluetoothAdapter.cancelDiscovery();
                    tV_search.setText("重新搜索");
                } else {
                    myModles.clear();
                    myAdapter.notifyDataSetChanged();

                    Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
                    if (pairedDevices.size() > 0) {
                        for (BluetoothDevice device : pairedDevices) {
                            myModles.add(new MyModle(device.getAddress(), device.getName()));
                            myAdapter.notifyDataSetChanged();
                        }
                    } else {
                        myAdapter.notifyDataSetChanged();
                    }
                    /* 开始搜索 */
                    bluetoothAdapter.startDiscovery();
                    tV_search.setText("停止搜索");
                }
                break;
        }
    }


    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // If it's already paired, skip it, because it's been listed already
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    myModles.add(new MyModle(device.getAddress(), device.getName()));
                    myAdapter.notifyDataSetChanged();
                }
                // When discovery is finished, change the Activity title
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setProgressBarIndeterminateVisibility(false);
                tV_search.setText("重新搜索");
            }
        }
    };

}
